package com.example.customview.view

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.core.view.children
import kotlin.math.max

class TagLayout(context: Context?, attrs: AttributeSet?) : ViewGroup(context, attrs) {

    // 保存每个子 View 的位置信息
     var childrenBounds = mutableListOf<Rect>()


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        // 宽度累加 单行
        var totalUsedWidth = 0

        // 所有使用的高度累加
        var totalUsedHeight = 0

        // 已被使用的单行大小
        var widthUsedOfSingleLine = 0

        // 已被使用的单行最高的哪个
        var maxHeightOfSingleLine = 0

        val specWidthMode = MeasureSpec.getMode(widthMeasureSpec)
        val specWidthSize = MeasureSpec.getSize(widthMeasureSpec)
        for ((index, child) in children.withIndex()) {

            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, totalUsedHeight)

            // 需要换行
            if (specWidthMode != MeasureSpec.UNSPECIFIED
                && widthUsedOfSingleLine + child.measuredWidth > specWidthSize
            ) {
                widthUsedOfSingleLine = 0
                totalUsedHeight += maxHeightOfSingleLine
                maxHeightOfSingleLine = 0
                measureChildWithMargins(
                    child,
                    widthMeasureSpec,
                    0,
                    heightMeasureSpec,
                    totalUsedHeight
                )
            }

            // 避免为空
            if (index >= childrenBounds.size) {
                childrenBounds.add(Rect())
            }
            // 为每个child 保存位置信息
            val rect = childrenBounds[index]
            rect.set(
                widthUsedOfSingleLine,
                totalUsedHeight,
                widthUsedOfSingleLine + child.measuredWidth,
                totalUsedHeight + child.measuredHeight
            )

            widthUsedOfSingleLine += child.measuredWidth
            totalUsedWidth = max( totalUsedWidth,widthUsedOfSingleLine)
            maxHeightOfSingleLine = max(maxHeightOfSingleLine, child.measuredHeight)
        }
        val selfWidth = totalUsedWidth
        val selfHeight = maxHeightOfSingleLine + totalUsedHeight
        setMeasuredDimension(selfWidth, selfHeight)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        for ((index, child) in children.withIndex()) {
            val childBound = childrenBounds[index]
            child.layout(childBound.left, childBound.top, childBound.right, childBound.bottom)
        }

    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }

//    override fun generateLayoutParams(p: LayoutParams?): LayoutParams {
//        return MarginLayoutParams(p)
//    }

    override fun shouldDelayChildPressedState(): Boolean {
        return false
    }
}